import { history, setLocale } from 'umi';
import { useUrlParams } from './utils';

export function onRouteChange(router: any) {
  //  用于解决语言和路由对应问题

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const lang = useUrlParams('lang');
  const { pathname, search, state } = router.location;

  if (!lang) {
    const key = `${pathname?.includes('/en') ? `en-US` : 'zh-TW'}`;

    const newUrl = `${pathname}${search ? `${search}&lang=${key}` : `?lang=${key}`}`;
    setLocale(key);
    history.replace(newUrl, { ...state });
  } else {
    setLocale(lang);
  }
  //  切换页面，回到顶部
  window.scrollTo(0, 0);
}
